package seckill

import (
	"context"
	"go.uber.org/zap"
	"srv/config"
	"srv/internal/hander/service"
	"srv/internal/model/dao"
	__ "srv/proto"
)

// 定义空接口
type SeckillService struct {
	__.UnimplementedSeckillServiceServer
}

// 实现方法
func (s *SeckillService) SeckillAdd(ctx context.Context, req *__.SeckillAddRequest) (resp *__.SeckillAddResponse, err error) {
	config.DB.Begin() //开启事务
	var event dao.LsSeckillEvent
	config.DB.Where("seckill_events_name=?", req.Name).Limit(1).Find(&event)
	if event.Id != 0 {
		zap.S().Error("该活动已经存在")
		config.DB.Rollback() //失败的话进行返回
		return
	}
	seckillEvent := dao.LsSeckillEvent{
		SeckillTimeId:           int(req.SeckillTime),
		SeckillEventsName:       req.Name,
		SeckillEventsNote:       req.Note,
		SeckillEventsQuta_Code:  req.Code,
		SeckillEventsQuotaCount: int(req.Count),
	}
	tx := config.DB.Create(&seckillEvent)
	if tx.Error != nil {
		zap.S().Error("活动创建失败")
		config.DB.Rollback()
		return
	}
	config.DB.Commit()
	return &__.SeckillAddResponse{Id: int64(seckillEvent.Id)}, nil
}

// 实现方法
func (s *SeckillService) SeckillList(ctx context.Context, req *__.SeckillListRequest) (resp *__.SeckillListResponse, err error) {
	config.DB.Begin() //开启事务
	var event []*__.SeckillList
	config.DB.Where("goodSpecValueId=?", req.Id).Scopes(service.Paginate(1, 2)).Find(&event)
	if event == nil {
		zap.S().Error("该活动已结束")
		config.DB.Rollback() //失败的话进行返回
		return
	}
	return &__.SeckillListResponse{List: event}, nil
}
